﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Litografia.BusinessComponents;
using Litografia.BusinessEntities;

namespace Litografia.UI
{

    public partial class SearchForm : Form
    {
        #region Declarations

        private readonly EntityType entity;

        private const int columnaId = 0;
        private const int columnaNombre = 1;

        #endregion

        #region Properties: Public

        public string SelectedId { get; set; }
        public string SelectedCode { get; set; }
        public string SelectedName { get; set; }
        
        #endregion

        #region Constructors

        private SearchForm()
        {
            InitializeComponent();
        }

        public SearchForm(EntityType entity)
            : this()
        {
            this.entity = entity;
        }

        #endregion

        #region Event Handlers

        private void BusquedaForm_Load(object sender, EventArgs e)
        {   
            Text += entity;
            ConfigureGrid();
        }

        private void SearchForm_Activated(object sender, EventArgs e)
        {
            if (dataGrid.Rows.Count > 0)
                dataGrid.Focus();
            else
                filtroTextBox.Focus();
        }

        private void AceptarButton_Click(object sender, EventArgs e)
        {
            if (dataGrid.SelectedRows.Count == 1)
            {
                SelectedId = dataGrid.SelectedRows[0].Cells[columnaId].Value.ToString(); 
                SelectedName = dataGrid.SelectedRows[0].Cells[columnaNombre].Value.ToString(); 
                Close();
            }
        }

        private void dataGrid_KeyPress(object sender, KeyPressEventArgs e)
        {
            AceptarButton.PerformClick();
        }

        private void dataGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            AceptarButton.PerformClick();
        }

        private void buscarButton_Click(object sender, EventArgs e)
        {
            var results = BCSearch.GetEntities(entity, filtroTextBox.Text.Trim());
            dataGrid.DataSource = results;

            if (results.Count > 0)
                dataGrid.Focus();
            else
                filtroTextBox.Focus();
        }

        private void filtroTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                buscarButton.PerformClick();
        }

        #endregion

        #region Methods: Non-Public

        private void ConfigureGrid()
        {
            dataGrid.DataSource = new List<BEEntity>();
            dataGrid.Columns[columnaId].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGrid.Columns[columnaNombre].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }


        #endregion

    }
}
